import React, { Component } from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'

import HomeList from '../../../components/HomeList'
import LoadMore from '../../../components/LoadMore'
import { getSearchData } from '../../../fetch/search/search'

const initalState = {
  data: [],
  hasMore: false,
  isLoadingMore: false,
  page: 0
}

class SearchList extends Component {
  constructor(props) {
    super(props);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
    this.state = initalState;
  }

  componentDidMount() {
    this.loadPageData();
  }

  // 加载第一页数据
  loadPageData() {
    console.log(this);
    const cityName = this.props.userInfo.cityName;
    const result = getSearchData(cityName, 0);
    this.handleResult(result);
  }

  // 加载更多
  loadMoreData() {
    this.setState({
      isLoadingMore: true
    });
    const cityName = this.props.userInfo.cityName;
    const result = getSearchData(cityName, this.state.page);
    this.handleResult(result);
  }

  handleResult(result) {
    const page = this.state.page
    this.setState({
      page: page + 1
    })

    result.then(res => {
      return res.json()
    }).then(json => {
      const hasMore = json.hasMore;
      const data = json.data;
      this.setState({
        hasMore: hasMore,
        data: this.state.data.concat(data),
        isLoadingMore: false
      })
    }).catch(ex => {
      if(__DEV__) {
        console.error('获取猜你喜欢数据出现异常');
      }
    })
  }

  render() {
    return (
      <div>
        {
          this.state.data.length
          ? <HomeList data={this.state.data}/>
          : <div>加载中...</div>
        }
        {
          this.state.hasMore
          ? <LoadMore isLoadingMore={this.state.isLoadingMore} loadMore={this.loadMoreData.bind(this)}/>
          : ''
        }
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    userInfo: state.userInfo
  }
}

const mapDispatchToProps = (dispatch) => {
  return {}
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SearchList)
